<template>
  <div class="login-box">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <h1 class="login-title">欢迎登录</h1>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="form.name" placeholder="请输入用户名" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password"  placeholder="请输入密码" v-model="form.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        form: {
          name: '',
          pass: '',
        },
        rules: {
          name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
          ],
          pass: [
            { required: true, message: '请输入登录密码', trigger: 'blur' },
            { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //this指向有问题，需要在函数前定义
            const that=this
            this.axios({
              method : "post",
              url:'http://localhost:8090/login',
              data:{
                name:this.form.name,
                pass:this.form.pass
              }
            }).then(function (res) {
              if(res.data=='success'){
                console.log(res.data)
                that.$router.push("/home")
              }else {
                that.$message.error('用户名或密码错误！');
                return false;
              }
            })
          }
        });
      }
    }
  }
</script>

<style scoped>
  .login-box{
    width: 500px;
    height: 400px;
    border: 1px solid #DCDFE6;
    margin: 150px auto;
    padding: 20px 50px 20px 30px;
    border-radius: 20px;

  }
  .login-title{
    text-align: center;
    margin-bottom: 60px;
  }
</style>
